package com.example.common.recycler.decoration;

import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 只适用于为RecyclerView增加水平垂直透明间距,且itemView是宽度是match_parent的情况
 */
public class GridMatchItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int horizontalSpace;
    private int verticalSpace;

    /**
     * 网格的列数
     *
     * @param spanCount
     */
    public void setSpanCount(int spanCount) {
        this.spanCount = spanCount;
    }

    /**
     * 水平间隔
     *
     * @param horizontalSpace px
     */
    public void setHorizontalSpace(int horizontalSpace) {
        this.horizontalSpace = horizontalSpace;
    }

    /**
     * 垂直间隔
     *
     * @param verticalSpace px
     */
    public void setVerticalSpace(int verticalSpace) {
        this.verticalSpace = verticalSpace;
    }

    public GridMatchItemDecoration(int spanCount, int horizontalSpace, int verticalSpace) {
        this.spanCount = spanCount;
        this.horizontalSpace = horizontalSpace;
        this.verticalSpace = verticalSpace;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int pos = parent.getChildAdapterPosition(view);
        if (pos > spanCount - 1) {
            outRect.top = verticalSpace;
        }
        if (pos % spanCount < spanCount - 1) {
            outRect.right = horizontalSpace;
        }
    }

}